package lfp.service.sender;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 * User: zhangsiyuan
 * Date: 2007-7-13
 * Time: 0:34:15
 */
public class SenderClient {
    private static Logger log = Logger.getLogger(SenderClient.class);

    private Socket client;

    public SenderClient(String hostname, int port) {
        try {
            client = new Socket(hostname, port);
        } catch (IOException e) {
            log.warn(e);
        }
    }

    public boolean sender(String dataToBeSend) {
        DataOutputStream os;
        if (client == null) return false;
        try {
            os = new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            log.warn(e);
            return false;
        }
        try {
            os.writeBytes(dataToBeSend);
        } catch (IOException e) {
            log.warn(e);
            return false;
        }
        try {
            os.close();
        } catch (IOException e) {
            log.info(e);
        }
        return true;
    }

    public String response() {
        if (client == null) return null;
        String str = null;
        BufferedReader is;
        try {
            is = new BufferedReader(new InputStreamReader(client.getInputStream()));
            str = is.readLine();
        } catch (IOException e) {
            log.warn(e);
        }
        return str;
    }

    public void closeSocket() {
        if (client == null) return;
        try {
            client.close();
        } catch (IOException e) {
            log.warn(e);
        }
    }

    public Socket getClient() {
        return client;
    }

//    public static SenderClient getInstance() {
//        int maxHostNum = 4;
//        ResourceBundle bundle = PropertyResourceBundle.getBundle("config.serverHost");
//        String marker = "server.hostName";
//        String hostName;
//        int port = Integer.valueOf(bundle.getString("server.port"));
//        SenderClient senderClient = null;
//        for (int i = 1; i <= maxHostNum; i++) {
//            try {
//                hostName = bundle.getString(marker + i);
//            } catch (NullPointerException e) {
//                log.info("can't find available host!");
//                return senderClient;
//            }
//            while (!bConnected) {
//                senderClient = new SenderClient(hostName, port);
//                if (senderClient.getClient() != null) {
//                    bConnected = true;
//                    break;
//                }
//            }
//        }
//        return senderClient;
//    }
//

}
